<?php

namespace app\model;

use think\Model;

class WorkHour extends Model
{
    protected $autoWriteTimestamp = true;

    public static function createDataByExcel($data)
    {
        // 启动事务
        self::startTrans();
        try {
            $i = 0;
            foreach ($data as $k => $v) {
                $i++;

                $is_exist = self::where('time', strtotime($v['B']))->where('id_num', $v['C'])->find();
                if (!empty($is_exist)) {
                    self::where('id', $is_exist['id'])
                        ->update(['name' => $v['A'], 'time' => strtotime($v['B']), 'id_num' => $v['C'], 'service_unit' => $v['D'], 'work_hour' => $v['E'], 'update_time' => date('Y-m-d H:i:s', time())]);
                } else {
                    self::create(['name' => $v['A'], 'time' => strtotime($v['B']), 'id_num' => $v['C'], 'service_unit' => $v['D'], 'work_hour' => $v['E']]);
                }
            }
            // 提交事务
            self::commit();
            return $i;
        } catch (\Exception $e) {
            // 回滚事务
            self::rollback();
            // error($e->getMessage());
            error('第'.$i.'条数据错误');
        }
    }

    /**
     * 获取工时列表
     *
     * @param [type] $time
     * @return void
     */
    public static function getList($time, $id_num = [])
    {
        $page = input('page');
        if (empty($page)) {
            $page = 1;
        }
        $limit = input('limit');
        if (empty($limit)) {
            $limit = 10;
        }
        $page_count = ($page - 1) * $limit;

        $where[] = ['time', '=', $time];
        if (!empty($id_num)) {
            $where[] = ['id_num', 'in', $id_num];
        }
        $name = input('name');
        if (!empty($name)) {
            $where[] = ['name', 'like', "%{$name}%"];
        }

        $list['data'] = self::where($where)
            ->withAttr('time', function($value, $data) {
                return date('m', $value);
            })
            ->limit($page_count, $limit)
            ->select();
        $list['all_work_hour'] = self::where($where)->sum('work_hour');
        $list['count'] = self::where($where)->count();
        $list['page'] = $page;
        return $list;
    }
}
